package top.yaofengqiao.springcloudsimple.web.starter.config;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.yaofengqiao.springcloudsimple.web.starter.exception.GlobalExceptionHandler;

/**
 * @author yfq
 * @date 2024/6/4 16:14
 * @description
 */
public class SimpleWebAutoConfiguration implements WebMvcConfigurer {
    /**
     * 全局异常处理器
     */
    @Bean
    public GlobalExceptionHandler globalExceptionHandler() {
        return new GlobalExceptionHandler();
    }

    /**
     * 接口前缀配置
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher antPathMatcher = new AntPathMatcher(".");

        // 为http.admin包下的controller加上/admin前缀
        configurer.addPathPrefix("/admin", clazz -> isController(clazz) && antPathMatcher.match("**.http.admin.**", clazz.getPackage().getName()));

        // 为http.app包下的controller加上/app前缀
        configurer.addPathPrefix("/app", clazz -> isController(clazz) && antPathMatcher.match("**.http.app.**", clazz.getPackage().getName()));
    }

    private boolean isController(Class<?> clazz) {
        return clazz.isAnnotationPresent(RestController.class) || clazz.isAnnotationPresent(Controller.class);
    }

}
